package net.csdn.business.auth.component;

import cn.hutool.core.util.StrUtil;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;

import java.util.ArrayList;
import java.util.List;


/**
 * @Desc: ignoreUrls
 * @ClassName: PermitAllUrlResolver
 * @Author: yourleige@163.com
 * @Date: 2022/9/26 10:28
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
@ConfigurationProperties(prefix = "security.oauth2.client")
public class PermitAllUrlResolver{
	@Getter
	@Setter
	private List<String> ignoreUrls = new ArrayList<>();


	/**
	 * @Desc: 对外暴露的URL注册到 springsecurity过滤器链中
	 * @Author: zhangyalei
	 * @Date: 2022/9/26 10:58
	 */
	public void registry(ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry) {
		for (String url : getIgnoreUrls()) {
			String[] strings = StrUtil.splitToArray(url, "|");
			//仅配置对外暴露的URL则注册到 spring security的为全部方法
			if (strings.length == 1) {
				registry.antMatchers(strings[0]).permitAll();
				continue;
			}
			//当配置对外的URL|GET,POST这种形式则获取方法列表并注册到springsecurity过滤器链中
			if (strings.length == 2) {
				for (String method : StrUtil.split(strings[1], StrUtil.COMMA)) {
					registry.antMatchers(HttpMethod.valueOf(method), strings[0]).permitAll();
				}
				continue;
			}
			log.warn("{} 配置无效，无法配置对外暴露", url);
		}
	}

}
